<?php
//
// +---------------------------------------------------------------------------------+
// | Package: EezeeSite Core                                                         |
// +---------------------------------------------------------------------------------+
// | Copyright (C) 2006  EezeeSite Development Team                                  |
// +---------------------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or                   |
// | modify it under the terms of the GNU General Public License                     |
// | as published by the Free Software Foundation; either version 2                  |
// | of the License, or (at your option) any later version.                          |
// |                                                                                 |
// | This program is distributed in the hope that it will be useful,                 |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of                  |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                   |
// | GNU General Public License for more details.                                    |
// |                                                                                 |
// | You should have received a copy of the GNU General Public License               |
// | along with this program; if not, write to the Free Software                     |
// | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. |
// +---------------------------------------------------------------------------------+
// | Author: Mayukh De <mayukhde@gmail.com>                                          |
// +---------------------------------------------------------------------------------+
//

class ESSystemInstaller extends ESSystem
{
    var $checkListType = 'clientCheckList';
    var $AJAXResponse;
    
    function ESSystemInstaller()
    {
        $this->AJAXResponse = new HTML_AJAX_Action();
        return;
    }
    
    function getCurrentInstallStep()
    {
        foreach ($this->clientCheckList as $k => $v) {
            $currentStepData = call_user_func(array(&$this, $v.'Step'));
            if (is_array($currentStepData)) {
                return $currentStepData;
            }
        }
    }

    function configStep()
    {
        if (!file_exists(ES_CONFIG_FILE)) {
            $data['STEPNAME'] = 'Site Configuration Settings';
            $data['CONTENTS'] = 'configcreate';
            return $data;
        } else {
            return;
        }        
    }
    
    function DBStep()
    {
        global $ESDB;
        if (!$ESDB || PEAR::isError($ESDB)) {
            $data['STEPNAME'] = 'DB Setup';
            $data['CONTENTS'] = 'dbcreate';
            return $data;
        } else {
            return;
        }       
    }
    
    function tablesStep()
    {
        global $ESDB;
        global $DBSchemaConfigs;
        $sql = 'SHOW TABLES LIKE \''.ES_TBL_PRE.'%\';';
        $result = $ESDB->query($sql);
        $numTables = $result->numRows();
        if ($numTables == 0) {
            $data['STEPNAME'] = 'Setting Up the Required Tables and Default Values';
            $data['CONTENTS'] = 'tablescreate';
            return $data;
        } else {
            return;
        }        
    }
    
    function tplsStep()
    {
        return;
    }
    
    function htaccessStep()
    {
        if (!file_exists(ES_INSTALL_DIR.'/.htaccess') && $GLOBALS['ES']['CLIENTCONF']['rewrite_url'] = '1') {
            $data['STEPNAME'] = 'Installing Resources for Search Engine Friendly URLs';
            $data['CONTENTS'] = 'htaccesscreate';
            return $data;            
        } else {
            return;
        }        
    }
    
    function installLockStep()
    {
        if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/../inc/'.md5(ES_BASE_URL).'.lock')) {
            $data['FINALSTEP'] = true;
            return $data;
        } else {
            return;
        }        
    }    
    
    function installConfigFile($input)
    {
        $config = new Config();
        $options = array('name' => 'GLOBALS[\'ES\'][\'CLIENTCONF\']');
        $config->parseConfig($input, 'PHPArray', $options);
        if ($config->writeConfig(ES_CONFIG_FILE, 'PHPArray')) {
            return true;
        } else {
            return false;
        }        
    }
    
    function installDB($input)
    {
        switch ($input['db_action']) {
        case '1':
            $GLOBALS['ES']['CLIENTCONF']['db_host'] = $input['db_host'];
            $GLOBALS['ES']['CLIENTCONF']['db_name'] = $input['db_name'];
            $GLOBALS['ES']['CLIENTCONF']['db_user_name'] = $input['db_user_name'];
            $GLOBALS['ES']['CLIENTCONF']['db_password'] = $input['db_password'];
            $GLOBALS['ES']['CLIENTCONF']['db_port'] = $input['db_port'];
            $config = new Config();
            $options = array('name' => 'GLOBALS[\'ES\'][\'CLIENTCONF\']');
            $config->parseConfig($GLOBALS['ES']['CLIENTCONF'], 'PHPArray', $options);
            $config->writeConfig(ES_CONFIG_FILE, 'PHPArray');
            $DBPort = ($GLOBALS['ES']['CLIENTCONF']['db_port'] && !empty($GLOBALS['ES']['CLIENTCONF']['db_port'])) ? ':'.$GLOBALS['ES']['CLIENTCONF']['db_port'] : null;
            $dsn = strtolower($GLOBALS['ES']['CLIENTCONF']['db_type']).'://'.$GLOBALS['ES']['CLIENTCONF']['db_user_name'].':'.$GLOBALS['ES']['CLIENTCONF']['db_password'].'@'.$GLOBALS['ES']['CLIENTCONF']['db_host'].$DBPort.'/'.$GLOBALS['ES']['CLIENTCONF']['db_name'];
            $tempDB = DB::connect($dsn);
            if (!$tempDB || PEAR::isError($tempDB)) {
                $return['MODE']    = $input['db_action'];
                $return['SUCCESS'] = false;
            } else {
                $return['MODE']    = $input['db_action'];
                $return['SUCCESS'] = true;
            }
            break;
        case '2':
            $DBPort = ($GLOBALS['ES']['CLIENTCONF']['db_port'] && !empty($GLOBALS['ES']['CLIENTCONF']['db_port'])) ? ':'.$GLOBALS['ES']['CLIENTCONF']['db_port'] : null;
            $dsn = strtolower($GLOBALS['ES']['CLIENTCONF']['db_type']).'://'.$GLOBALS['ES']['CLIENTCONF']['db_user_name'].':'.$GLOBALS['ES']['CLIENTCONF']['db_password'].'@'.$GLOBALS['ES']['CLIENTCONF']['db_host'].$DBPort;
            $tempDB = DB::connect($dsn);
            $sql = 'CREATE DATABASE `'.$GLOBALS['ES']['CLIENTCONF']['db_name'].'`;';
            $result = $tempDB->query($sql);
            if (DB::isError($result)) {
                $return['MODE']    = $input['db_action'];
                $return['SUCCESS'] = false;
            } else {
                $return['MODE']    = $input['db_action'];
                $return['SUCCESS'] = true;
            }        
            break;
        }
        return $return;
    }
    
    function installTables()
    {
        global $ESDB;
        $DBOps = new ESDBOps($ESDB, 'dummy');
        $message = $DBOps->createDBTables();
        $this->insertDefaults();
        return $message;
    }
    
    function insertDefaults()
    {
        global $ESPerms;
        global $ESDB;
        $application = array(
                            'application_id'          => 1,
                            'application_define_name' => $GLOBALS['ES']['CLIENTCONF']['site_title']
                            );
        $applicationID = $ESPerms->addApplication($application);
        $anonymousGroup = array(
                               'group_id'          => 0,
                               'group_define_name' => 'Non-members'
                               );
        $anonymousGroupID = $ESPerms->addGroup($anonymousGroup);
        $adminGroup = array(
                           'group_id'          => 1,
                           'group_define_name' => $GLOBALS['ES']['CLIENTCONF']['admin_group']
                           );
        $adminGroupID = $ESPerms->addGroup($adminGroup);
        $regUserGroup = array(
                             'group_id'          => 2,
                             'group_define_name' => $GLOBALS['ES']['CLIENTCONF']['member_group']
                             );
        $regUserGroupID = $ESPerms->addGroup($regUserGroup);        
        $anonymousUser = array(
                              'perm_user_id'        => 0,
                              'auth_user_id'        => 0,
                              'perm_type'           => $anonymousGroupID,
                              'auth_container_name' => 'DB'
                              );
        $anonymousUserID = $ESPerms->addUser($anonymousUser);
        $adminUser = array(
                          'perm_user_id'        => 1,
                          'auth_user_id'        => 1,
                          'perm_type'           => $adminGroupID,
                          'auth_container_name' => 'DB'
                          );
        $adminUserID = $ESPerms->addUser($adminUser);
        $anonymousUserToGroup = array(
                                     'perm_user_id' => 0,
                                     'group_id'     => $anonymousGroupID
                                     );
        $ESPerms->addUserToGroup($anonymousUserToGroup);
        $adminUserToGroup = array(
                                 'perm_user_id' => 1,
                                 'group_id'     => $adminGroupID
                                 );
        $ESPerms->addUserToGroup($adminUserToGroup);
        $usersDB = new ESDBOps($ESDB, ES_USERS_TBL);
        $usersDB->resetVars(ES_USERS_TBL);
        $anonVals = array(
                         'user_id'    => 0,
                         'handle'     => 'Anonymous',
                         'email'      => 'Anonymous',
                         'password'   => md5('password'),
                         'lastaccess' => time(),
                         'lastcookie' => $_COOKIE[$GLOBALS['ES']['CLIENTCONF']['cookie_name'].'_SESSION'],
                         'lastip'     => $_SERVER['REMOTE_ADDR'],
                         'is_active'  => 0,
                         'user_group' => $anonymousGroupID
                         );
        $anonymousID = $usersDB->insert($anonVals);
        $adminVals = array(
                          'user_id'    => 1,
                          'handle'     => strtolower($GLOBALS['ES']['CLIENTCONF']['admin_name']),
                          'email'      => $GLOBALS['ES']['CLIENTCONF']['admin_email'],
                          'password'   => md5($GLOBALS['ES']['CLIENTCONF']['admin_password']),
                          'lastaccess' => time(),
                          'lastcookie' => $_COOKIE[$GLOBALS['ES']['CLIENTCONF']['cookie_name'].'_SESSION'],
                          'lastip'     => $_SERVER['REMOTE_ADDR'],
                          'is_active'  => 1,
                          'user_group' => $adminGroupID
                          );
        $adminID = $usersDB->insert($adminVals);
        $usersInfoDB = new ESDBOps($ESDB, ES_USERSXTRAINFO_TBL);
        $usersInfoDB->resetVars(ES_USERSXTRAINFO_TBL);
        $anonsXtraVals = array(
                              'user_id'    => 0,
                              'signupdate' => time(),
                              'updates'    => 0,
                              'lastupdate' => time(),
                              'searchable' => 0
                              );
        $usersInfoDB->insert($anonsXtraVals);
        $adminXtraVals = array(
                              'user_id'    => 1,
                              'signupdate' => time(),
                              'updates'    => 0,
                              'lastupdate' => time(),
                              'searchable' => 1
                              );
        $usersInfoDB->insert($adminXtraVals);
        $adminArea = array(
                          'application_id'   => $applicationID,
                          'area_define_name' => $GLOBALS['ES']['PERM']['AREAS'][0]
                          );
        $adminAreaID = $ESPerms->addArea($adminArea);        
        $personalArea = array(
                             'application_id'   => $applicationID,
                             'area_define_name' => $GLOBALS['ES']['PERM']['AREAS'][1].'_'.$adminID
                             );
        $personalAreaID = $ESPerms->addArea($personalArea);
        for ($i = 0; $i < count($GLOBALS['ES']['PERM']['AREAPERMS']['ADMIN']['LEVEL1']); $i++) {
            $rightOpts = array(
                              'area_id'           => $adminAreaID,
                              'right_define_name' => $GLOBALS['ES']['PERM']['AREAPERMS']['ADMIN']['LEVEL1'][$i]
                              );
            $rightID[$i] = $ESPerms->addright($rightOpts);
            $newRightOpt = array(
                                'group_id' => $adminGroupID,
                                'right_id' => $rightID[$i]
                                );
            $ESPerms->grantGroupRight($newRightOpt);
        }
        $rightID = null;
        for ($i = 0; $i < count($GLOBALS['ES']['PERM']['AREAPERMS']['ADMIN']['LEVEL2']); $i++) {
            $rightOpts = array(
                              'area_id'           => $adminAreaID,
                              'right_define_name' => $GLOBALS['ES']['PERM']['AREAPERMS']['ADMIN']['LEVEL2'][$i]
                              );
            $rightID[$i] = $ESPerms->addright($rightOpts);
            $newRightOpt = array(
                                'perm_user_id' => 1,
                                'right_id'     => $rightID[$i]
                                );
            $ESPerms->grantUserRight($newRightOpt);
        }
        $rightID = null;
        for ($i = 0; $i < count($GLOBALS['ES']['PERM']['AREAPERMS']['USER']['LEVEL1']); $i++) {
            $rightOpts = array(
                              'area_id'           => $personalAreaID,
                              'right_define_name' => $GLOBALS['ES']['PERM']['AREAPERMS']['USER']['LEVEL1'][$i]
                              );
            $rightID[$i] = $ESPerms->addright($rightOpts);
        }
        $rightID = null;
        for ($i = 0; $i < count($GLOBALS['ES']['PERM']['AREAPERMS']['USER']['LEVEL2']); $i++) {
            $rightOpts = array(
                              'area_id'           => $personalAreaID,
                              'right_define_name' => $GLOBALS['ES']['PERM']['AREAPERMS']['USER']['LEVEL2'][$i]
                              );
            $rightID[$i] = $ESPerms->addright($rightOpts);
            $newRightOpt = array(
                                'group_id' => $regUserGroupID,
                                'right_id' => $rightID[$i]
                                );
            $ESPerms->grantGroupRight($newRightOpt);
        }
        $rightID = null;
        for ($i = 0; $i < count($GLOBALS['ES']['PERM']['AREAPERMS']['USER']['LEVEL3']); $i++) {
            $rightOpts = array(
                              'area_id'           => $personalAreaID,
                              'right_define_name' => $GLOBALS['ES']['PERM']['AREAPERMS']['USER']['LEVEL3'][$i]
                              );
            $rightID[$i] = $ESPerms->addright($rightOpts);
            $newRightOpt = array(
                                'perm_user_id' => 1,
                                'right_id'     => $rightID[$i]
                                );
            $ESPerms->grantUserRight($newRightOpt);
        }
        /*$countOfAdminRights = count($GLOBALS['ES']['PERM']['AREAPERMS']['ADMIN']);
        for ($i = 0; $i < $countOfAdminRights; $i++) {
            $rightOpts = array(
                              'area_id'           => $adminAreaID,
                              'right_define_name' => $GLOBALS['ES']['PERM']['AREAPERMS']['ADMIN'][$i]
                              );
            $rightID[$i] = $ESPerms->addright($rightOpts);
            $newRightOpt = array(
                                'group_id' => $adminGroupID,
                                'right_id' => $rightID[$i]
                                );
            $ESPerms->grantGroupRight($newRightOpt);
        }
        $allPersonalRights = array_merge($GLOBALS['ES']['PERM']['AREAPERMS']['USER']['LEVEL1'], $GLOBALS['ES']['PERM']['AREAPERMS']['USER']['LEVEL3']);
        $countAllPersonalRights = count($allPersonalRights);
        for ($i = 0; $i < $countAllPersonalRights; $i++) {
            $rightOpts = array(
                              'area_id'           => $personalAreaID,
                              'right_define_name' => $allPersonalRights[$i]
                              );
            $rightID[$i] = $ESPerms->addright($rightOpts);
            $newRightOpt = array(
                                'perm_user_id' => 1,
                                'right_id'     => $rightID[$i]
                                );
            $ESPerms->grantUserRight($newRightOpt);
        }
        $countLevel2Rights = count($GLOBALS['ES']['PERM']['AREAPERMS']['USER']['LEVEL2']);
        for ($i = 0; $i < $countLevel2Rights; $i++) {
            $rightOpts = array(
                              'area_id'           => $personalAreaID,
                              'right_define_name' => $GLOBALS['ES']['PERM']['AREAPERMS']['USER']['LEVEL2'][$i]
                              );
            $ESPerms->addright($rightOpts);
        }*/
        return;
    }
    
    function installHtaccess()
    {
        global $ESController;
        $directives = "# This .htaccess file was created automatically by the EezeeSite installation process";
        $directives.= "\n# DO NOT MODIFY OR DELETE THIS FILE UNLESS YOU ARE ABSOLUTELY SURE OF WHAT YOU ARE DOING";
        $directives.= "\n#";
        $phpTypes = (ES_FILE_EXTN != '.php') ? ES_FILE_EXTN.' .php .inc' : '.php .inc';
        $directives.= "\nAddType application/x-httpd-php ".$phpTypes;
        $directives.= "\nOptions +FollowSymLinks";
        $directives.= "\nRewriteEngine on";
        $directives.= "\n#";
        $directives.= $ESController->getURLRewriteRules();
        $directives.= "\n#";
        $directives.= "\nErrorDocument 404 error".ES_FILE_EXTN."?mode=404";
		$directives.= "\n";     
        if (is_writable(ES_INSTALL_DIR.'/.htaccess') || ESSystem::chmod(ES_INSTALL_DIR)) {
            if (!$handle = fopen(ES_INSTALL_DIR.'/.htaccess', 'a')) {
                $return['SUCCESS'] = false;
            }
            if (fwrite($handle, $directives) === FALSE) {
                $return['SUCCESS'] = false;
            } else {
                $return['SUCCESS'] = true;
            }
            fclose($handle);
        } else {
            $return['SUCCESS'] = false;
        }
        return $return;
    }
    
    function installLock()
    {
        $directives = "#";
        if (is_writable(file_exists($_SERVER['DOCUMENT_ROOT'].'/../inc/'.md5(ES_BASE_URL).'.lock')) || ESSystem::chmod($_SERVER['DOCUMENT_ROOT'].'/../inc')) {
            if (!$handle = fopen($_SERVER['DOCUMENT_ROOT'].'/../inc/'.md5(ES_BASE_URL).'.lock', 'a')) {
                $return['SUCCESS'] = false;
            }
            if (fwrite($handle, $directives) === FALSE) {
                $return['SUCCESS'] = false;
            } else {
                $return['SUCCESS'] = true;
            }
            fclose($handle);
        } else {
            $return['SUCCESS'] = false;
        }
        return $return;        
    }
    
    function checkInstallSession()
    {
        global $localSettings;
        session_start();
        if (isset($_SESSION['ES_INSTALL_SESS']) && $_SESSION['ES_INSTALL_SESS']['ADMIN'] = $localSettings['admin'] && $_SESSION['ES_INSTALL_SESS']['PASS'] = $localSettings['admin_pass']) {
            return true;
        } else {
            session_destroy();
            return false;
        }
    }
    
    function createInstallSession($input)
    {
        session_start();
        session_register('ES_INSTALL_SESS');
        $_SESSION['ES_INSTALL_SESS']['ADMIN'] = $input['admin_name'];
        $_SESSION['ES_INSTALL_SESS']['PASS']  = $input['admin_password'];
        return;
    }
}

?>